#coding=utf-8
from django.db import models
from share import Share
import scraper

class Exday(models.Model):
    
    date = models.DateField()
    share = models.ForeignKey(Share)
    pre = models.ForeignKey('self', unique=True, null=True, blank=True)
    
    def get_nextday(self):
        a = self.exday_set.all()
        if a:
            return a[0]
        return None
    next=property(fget=get_nextday)
    
    def get_price(self):
        a = self.price_set.all()
        if a:
            return a[0]
        return None
    price=property(fget=get_price)
    
    def get_ts(self):
        '''该交易日的流通A股数量'''
        s = self.share
        for t in s.tradableshare_set.all().order_by('-date'):
            if self.date >= t.date:
                return t.quantity
    ts = property(fget=get_ts)
    
    def get_avgprice(self):
        a = self.averageprice_set.all()
        if a:
            return a[0]
        return None
    avgprice=property(fget=get_avgprice)
    
    def get_avgvolume(self):
        a = self.averagevolume_set.all()
        if a:
            return a[0]
        return None
    avgvolume=property(fget=get_avgvolume)
    
    def prenday(self, n):
        cur = self
        for i in range(n):
            pre = cur.pre
            if not pre: return None
            cur = pre
        return cur 
    
    def has_deal(self):
        if self.deal_set.count() == 0:
            return False
        else:
            return True 
            
    def deal2db(self):
    def avgprice2db(self):pass
    def avgvolume(self):pass
        '''get dealdetails and put them in csv file, db
           if No deal On this Day. it will raise NoDealError
        '''
        data = scraper.get_deal(self.share.code, self.date.isoformat())
        #put data into csv file
        ddir = DEALDIR + '/%s'%self.share.code
        if not os.path.exists ( ddir ):os.mkdir(ddir)
        head = ['时间', '成交量', '成交价',	'性质']
        fn = ddir + '/%s.csv'%self.date.isoformat()
        data2csv(data, head, fn)
        
        #validation       
        for d in data:
            try:
                isValidDealfromSina(d)
            except ValidationError,e:
                print e
                print d                   
                data.remove(d)
                
        for d in data:
            dd = Deal(exday=self, time=d[0], volume=int(d[1]), price=float2dec(d[2], 2),  buyorsell=d[3])
            dd.save()
            
    def liveprice2db(self):
        '''get liveprice and put them in csv file, db'''
        rp, mm5d = get_rtprice(self.share.code)
        
        #need validation
        LivePrice(Exday=self, time=d[1])
    def __unicode__(self):
        jyr = unicode('交易日', 'u8')
        return "%s:%sof%s"%(self.date, jyr, self.share)
    
    class Admin:pass
    class Meta:
        app_label = 'shstock'    
